﻿using ECommon;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace EOrm.NpgsqlProvider
{
    /// <summary>
    /// postgres数据表构建工厂类
    /// </summary>
    public class PgTableFactory : ITableFactory
    {
        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <param name="isSeperated">数据库名称是否启用分割线命名法</param>
        /// <returns>数据表</returns>
        public ITable Create(Type entityType, bool isSeperated)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException("entityType", "创建数据表时实体类型不可为空");
            }
            ITable table = new PgTable();
            table.IsSeperated = isSeperated;
            table.Name = entityType.Name;
            table.DbName = isSeperated ? StringTool.ToSeparator(table.Name) : table.Name;
            List<PropertyInfo> properties = ReflectionTool.GetProperties(entityType);
            if (properties != null && properties.Count > 0)
            {
                VariableTypeMapper varMapper = new VariableTypeMapper();
                foreach (PropertyInfo property in properties)
                {
                    IField field = new PgField();
                    if (property.Name.ToLower() == "id" || property.Name.ToLower() == table.Name.ToLower() + "id")
                    {
                        field.IsKey = true;
                    }
                    else
                    {
                        field.IsKey = false;
                    }
                    field.IsNullable = TypeTool.IsTypeNullable(property.PropertyType);
                    field.DbTypeName = varMapper.VariableTypeMap(TypeTool.GetTypeName(property.PropertyType));
                    field.IsAutoFill = false;
                    field.IsSeperated = isSeperated;
                    field.Name = property.Name;
                    field.DbName = isSeperated ? StringTool.ToSeparator(field.Name) : field.Name;
                    table.Fields.Add(field);
                }
            }
            return table;
        }
    }
}
